<template>
	<div class="content">
		<div class="pageTableView" style="margin-top: 0">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>工单信息区</div>
				</div>
				<div class="pageTableButView">
					<el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
					<el-button @click="trigger('finish')" type="primary" :icon="Select"
										 v-if="paginatedData.status != 7">完成
					</el-button>
					<el-button @click="trigger('stop')" type="primary" :icon="Lock" v-if="paginatedData.status == 4">暂停
					</el-button>
					<el-button @click="trigger('report2')" type="primary" :icon="CaretRight"
										 v-if="paginatedData.status == 6">继续
					</el-button>
					<el-button @click="trigger('report')" type="primary" :icon="CaretRight"
										 v-if="paginatedData.status == 3">开工
					</el-button>
					<el-button @click="doWorkJobReport" type="primary" :icon="Calendar">报工</el-button>
					<el-button @click="doFeeding" type="primary" :icon="OfficeBuilding">投料</el-button>
					<el-button @click="returnFeeding" type="primary" :icon="FolderRemove">退料</el-button>
					<el-button @click="handleAdd" type="primary" :icon="DocumentCopy">质检</el-button>
					<el-button @click="forceOver" type="danger" :icon="SwitchButton">强制完结</el-button>
				</div>
			</div>
			<div class="info-body">
				<div class="info-cil">
					<div class="info-title">工单号</div>
					<div class="info-param">{{ paginatedData.workNo || '--' }}</div>
				</div>
				<div class="info-cil">
					<div class="info-title">产品名称</div>
					<div class="info-param">{{ paginatedData.productName || '--' }}</div>
				</div>
				<div class="info-cil">
					<div class="info-title">总数</div>
					<div class="info-param">{{ paginatedData.orderCount || '--' }}</div>
				</div>
				<div class="info-cil">
					<div class="info-title">已完成数量</div>
					<div class="info-param">{{ paginatedData.finishCount || '--' }}</div>
				</div>
			</div>
			<div class="info-body">
				<div class="info-cil">
					<div class="info-title">计划开始时间</div>
					<div class="info-param">{{ paginatedData.planBeginTime || '--' }}</div>
				</div>
				<div class="info-cil">
					<div class="info-title">计划结束时间</div>
					<div class="info-param">{{ paginatedData.planEndTime || '--' }}</div>
				</div>
				<div class="info-cil">
					<div class="info-title">实际开始时间</div>
					<div class="info-param">{{ paginatedData.actualBeginTime || '--' }}</div>
				</div>
				<div class="info-cil">
					<div class="info-title">实际结束时间</div>
					<div class="info-param">{{ paginatedData.actualEndTime || '--' }}</div>
				</div>
			</div>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>齐套状态区</div>
				</div>
			</div>
			<!-- 齐套状态区 -->
			<el-table :data="tableData" row-key="id" max-height="260px" header-cell-class-name="witheTableHeader">
				<el-table-column label="序号" align="center" type="index" width="70" />
				<el-table-column label="物料名称" prop="materialName" min-width="200" show-overflow-tooltip align="center" />
				<el-table-column label="物料编码" prop="materialNo" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="所需数量" prop="needNum" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="库存可用数量" prop="actualNum" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="库位编码" prop="storageCode" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column label="库位名称" prop="storageName" min-width="150" show-overflow-tooltip align="center" />
				<el-table-column prop="completeSetStatus" align="center" min-width="80" label="齐套状态"
												 :formatter="formatCompleteSetStatus" />
				<el-table-column label="库位名称" prop="storageName" min-width="150" show-overflow-tooltip
												 align="center" />
				<el-table-column label="库位编码" prop="storageCode" min-width="150" show-overflow-tooltip
												 align="center" />
				<el-table-column label="创建时间" prop="creatTime" min-width="150" show-overflow-tooltip align="center" />
			</el-table>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>投料信息区</div>
				</div>
			</div>
			<!-- 投料信息区 -->
			<el-table :data="tableData1" max-height="260px" border header-cell-class-name="witheTableHeader"
								style="width: 100%">
				<el-table-column type="index" label="序号" width="80" align="center" />
				<el-table-column prop="batchNo" label="批次号" align="center" width="250" />
				<el-table-column prop="materialName" label="物料名称" align="center" min-width="200"
												 show-overflow-tooltip />
				<el-table-column prop="materialCount" label="投料数量" align="center" />
				<el-table-column prop="createTime" label="投料时间" align="center" min-width="120" show-overflow-tooltip />
				<el-table-column prop="createUser" label="状态" width="150" align="center">
					<template #default="scope">
						<span> {{ scope.row.status == true ? '退料' : '投料' }} </span></template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>报工信息区</div>
				</div>
				<div class="pageTableButView">
					<el-button @click="revokeJob()" type="primary"
										 :disabled="reportList.length != 1 || reportList[0].isRevocation">撤销报工
					</el-button>
				</div>
			</div>
			<!-- 报工状态区 -->
			<el-table :data="tableData2" border max-height="260px" header-cell-class-name="witheTableHeader"
								@selection-change="handleSelectionChange" style="width: 100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="index" label="序号" width="80" align="center" />
				<el-table-column prop="reportWorkRecordNo" label="批次号" align="center" width="250" />
				<el-table-column prop="reportTraceCode" label="追溯码" align="center" min-width="150" />
				<el-table-column prop="count" label="报工数量" align="center" />
				<el-table-column prop="createTime" label="报工时间" align="center" />
				<el-table-column prop="materialOutName" label="产出物料" align="center" />
				<el-table-column prop="status" label="物料状态" :formatter="statusType" align="center" />
				<el-table-column prop="isRexocation" label="撤销报工" align="center" width="100">
					<template #default="scope">
						<span> {{ scope.row.isRevocation ? '已撤销' : '-' }} </span></template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">
					<div>质量信息区</div>
				</div>
			</div>
			<!-- 质量信息区 -->
			<el-table :data="tableData3" border max-height="260px" header-cell-class-name="witheTableHeader"
								style="width: 100%">
				<el-table-column type="index" label="序号" width="80" align="center" />
				<el-table-column prop="status" label="状态" min-width="100" align="center">
					<template #default="scope"> {{ scope.row.status ? '质检完成' : '未完成' }}</template>
				</el-table-column>
				<el-table-column prop="no" label="质检任务号" min-width="150" align="center" show-overflow-tooltip />
				<el-table-column prop="qualityType" label="质检类型" align="center" min-width="100">
					<template #default="scope">
						<span> {{ getQualityTypeByValue(scope.row.qualityType) }} </span></template>
				</el-table-column>
				<el-table-column prop="qualityReason" label="检测原因" align="center" show-overflow-tooltip>
					<template #default="scope">
            <span v-if="scope.row.qualityReason"> {{
								qualityReasonList.find(item => item.value == scope.row.qualityReason).label
							}} </span></template>
				</el-table-column>

				<el-table-column prop="passRate" label="合格率" align="center">
					<template #default="scope">
						<div v-if="scope.row.passRate"> {{ scope.row.passRate }}%
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="totalQuantity" label="检测数量" align="center" />
				<el-table-column prop="passQuantity" label="合格数量" align="center" />
				<el-table-column prop="failQuantity" label="不合格数量" align="center" />
				<el-table-column prop="compromiseQuantity" label="让步数量" align="center" />
				<el-table-column prop="scrapQuantity" label="报废数量" align="center" />
				<el-table-column prop="createTime" label="创建时间" min-width="200" align="center" />
			</el-table>
		</div>
		<!-- 编辑/新建弹框 -->
		<el-dialog v-model="showCrud" title="质检" width="800px">
			<el-form :model="formData" label-width="100px">
				<el-row :gutter="10">
					<el-col :span="12">
						<el-form-item label="质检类型" prop="procedureOrderId">
							<el-select v-model="formData.qualityType" placeholder="请选择质检类型" clearable filterable
												 style="width: 300px" @change="qualityTypeChange">
								<el-option key="1" label="首件检" value="1" />
								<el-option key="2" label="末件检" value="2" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="质检方案" prop="procedureOrderId">
							<el-select v-model="formData.qualityPlan" placeholder="请选择质检方案" clearable filterable
												 style="width: 300px" @change="qualityPlanChange">
								<el-option v-for="item in schemeTaskList" :key="item.id" :label="item.name"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if='formData.qualityType == 1'>
						<el-form-item label="检测原因" prop="qualityReason">
							<el-select v-model="formData.qualityReason" placeholder="请选择检测原因" clearable
												 style="width: 300px">
								<el-option v-for="(item, index) of qualityReasonList" :key="index" :label="item.label"
													 :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="质检方式" prop="qualityWay">
							<el-select v-model="formData.qualityWay" placeholder="请选择质检方式" clearable
												 style="width: 300px" disabled>
								<el-option v-for="(item, index) of qualityWayList" :key="index" :label="item.label"
													 :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="formData.qualityWay == 2">
						<el-form-item label="比例抽检">
							<el-input-number v-model="formData.proportionNumber" disabled :min="0" />
							（%）
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="formData.qualityWay == 3">
						<el-form-item label="固定抽检">
							<el-input-number v-model="formData.qualityNumber" :step="1" step-strictly :min="0" />
						</el-form-item>
					</el-col>
					<!--                    <el-col :span="12">-->
					<!--                        <el-form-item label="巡检间隔" prop="qualityInterval">-->
					<!--                            <el-input-number v-model="formData.qualityInterval" :step="1" step-strictly disabled /> （小时）-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->
					<el-col :span="24">
						<el-form-item label="方案说明" prop="qualityRemark" disabled>
							<el-input v-model="formData.qualityRemark" style="width: 718px" :rows="4" type="textarea"
												disabled placeholder="请输入方案说明" />
						</el-form-item>
					</el-col>
					<!--                    <el-col :span="12">-->
					<!--                        <el-form-item label="数量" prop="count">-->
					<!--                            <el-input-number v-model="formData.count" :min="0" />-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave">保存</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 查看详情弹框 -->
		<el-dialog v-model="showDetail" :title="crudTitle + '入库单'" width="1000px">
			<el-form :model="formData" label-width="100px">
				<el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="工序订单："> {{ formData.procedureOrderName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="出库库位："> {{ formData.sourceWarehouseName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="出库库位："> {{ formData.sourceStorageName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="入库库位："> {{ formData.targetWarehouseName || '--' }}</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="入库库位："> {{ formData.targetStorageName || '--' }}</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<div class="pageTableTitle">物料列表</div>
				</el-row>
				<el-row :gutter="10" style="padding: 10px">
					<el-table :data="formData.details" style="width:100% " height="calc(100vh - 600px)">
						<el-table-column label="序号" type="index" align="center" width="80" />
						<el-table-column prop="materialName" label="物料名称" align="center" />
						<el-table-column prop="materialCount" label="数量" align="center" width="150" />
						<el-table-column prop="batchNo" label="批次号" align="center" />
						<el-table-column align="center" width="110" fixed="right" v-if="popType != 1">
							<template #header>
								<el-button :icon="Plus" @click="handleAddConfigLine">新建</el-button>
							</template>
							<template #default="scope">
								<el-button type="danger" plain :icon="Delete" @click="handleConfigDelete(scope.$index)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="showDetail = false">关闭</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 点击入库弹窗 -->
		<el-dialog v-model="returnFeedingShow" title="退料" width="1200px">
			<el-form :model="returnFeedingForm" :rules="outInRules" ref="outInFormRef" label-width="100px">
				<el-row :gutter="10">
					<el-col :span="6">
						<el-form-item label="物料" prop="materialId" required>
							<el-select v-model="returnFeedingForm.materialId" clearable filterable placeholder="请选择物料"
												 @change="returnMaterChange">
								<el-option v-for="item in productBom" :key="item.id" :label="item.materialName"
													 :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="批次" prop="batchNo" required>
							<el-select v-model="returnFeedingForm.batchNo" placeholder="请选择" @change="bathNoChange">
								<el-option v-for="item in returnNoList" :key="item.batch" :label="item.batch"
													 :value="item.batch" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="已锁定数量"> {{ returnFeedingForm.lockCount }}</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="数量" prop="batchNo" required>
							<el-input-number :min="0" v-model="returnFeedingForm.count" :step="0.0001"
															 :precision="4"></el-input-number>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="returnFeedingShow = false">取消</el-button>
					<el-button type="primary" @click="outInSum(outInFormRef)">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { equipmentAll } from '@/api/scheduling/dispatchManagement';
import axiosInstance from '@/utils/http/api';
import {
	Calendar,
	CaretRight,
	ArrowLeft,
	Delete,
	DocumentCopy,
	Lock,
	OfficeBuilding,
	Plus,
	Select,
	SwitchButton,
	FolderRemove
} from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, reactive, ref } from 'vue';


const paginatedData = ref({});
const pageSize = ref(10);
const currentPage = ref(1);
const searchParam = ref({});

const formData = ref({
	planNo: '',
	name: '',
	planBeginTime: null,
	planEndTime: null,
	actualBeginTime: null,
	actualEndTime: null,
	organizationId: '',
	status: '0',
	type: '0'
});

const crudTitle = computed(() => {
	if (popType.value === 1) {
		return '查看';
	} else {
		return isEdit.value ? '编辑' : '新建';
	}
});

const showDetail = ref(false);


// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};
	currentPage.value = 1;
	// currentPage.value = 1
	getList();
};

const showOutIn = ref(false);
const outInForm = ref({
	materialName: '',
	materialCount: '',
	wareId: '',
	targetStorageId: '',
	batchNo: ''
});
const outInFormRef = ref(null);
const outInRules = reactive<FormRules<returnFeedingForm>>({
	count: [
		{ required: true, message: '请输入数量', trigger: 'blur' }
	],
	materialId: [
		{ required: true, message: '请选择物料', trigger: 'change' }
	],
	batchNo: [
		{ required: true, message: '请选择批次号', trigger: 'change' }
	]
});
const handleAddConfigLine = () => {
	formData.value.details.push({
		materialId: null,
		materialCount: null,
		batchNo: null
	});
};


import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();


const goBack = () => {
	router.go(-1);
};

const doWorkJobReport = () => {
	router.push(`/scheduling/workJobReport?id=${route.query.id}`);
};

const doFeeding = () => {
	router.push(`/scheduling/workPlanFeeding?id=${route.query.id}`);
};

const forceOver = () => {
	ElMessageBox.confirm('确认强制完结?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'error'
	})
		.then(() => {
			axiosInstance
				.post('/api/workOrder/constraintEnd', {
					id: route.query.id
				})
				.then((res) => {
					if (res.code === 200) {
						ElMessage.success('已强制完结');
					} else {
						ElMessage.warning(res.message);
					}
				});
		});
};

const trigger = (e) => {
	const showTitle = [
		{ value: 'stop', title: '暂停' },
		{ value: 'Revoke', title: '撤单' },
		{ value: 'report', title: '开工' },
		{ value: 'finish', title: '完成' },
		{ value: 'report2', title: '继续' }
	];
	let titleInfo = null;
	for (const item of showTitle) {
		if (e == item.value) {
			titleInfo = item.title;
		}
	}

	ElMessageBox.confirm('是否确认' + titleInfo + '?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
				if (e === 'stop') {
					axiosInstance
						.put('/api/workOrder/update', {
							id: route.query.id,
							status: 6
						})
						.then((res) => {
							if (res.code == 200) {
								ElMessage.success('暂停成功!');
								getList();

							} else {
								ElMessage.warning(res.message);
							}
						});
				}
				if (e === 'finish') {
					axiosInstance
						.post('/api/workOrder/updateAndproceStatus', {
							id: route.query.id,
							status: 7
						})
						.then((res) => {
							if (res.code === 200) {
								ElMessage.success('已完成');
								getList();

							} else {
								ElMessage.warning(res.message);
							}
						});
				}
				if (e === 'Revoke') {
					axiosInstance
						.post('/api/workOrder/revocationWork', {
							id: route.query.id
						})
						.then((res) => {
							if (res.code === 200) {
								ElMessage.success('已撤单');
								getList();

							} else {
								ElMessage.warning(res.message);
							}
						});
				}
				if (e === 'report' || e === 'report2') {
					axiosInstance
						.post('/api/basedataEquipment/queryByWorkOrder', {
							id: paginatedData.value.equipmentId,
							isWorkStatus: 'false'
						}).then(res => {
							const foundItem = res.data.find(item => item.id === route.query.id);
							if (res.data.indexOf(foundItem) !== 0) {
								ElMessageBox.confirm('当前工单不是设备下第一个工单，是否将当前工单置顶?', {
									confirmButtonText: '确定',
									cancelButtonText: '取消',
									type: 'warning'
								})
									.then(() => {
										axiosInstance
											.post('/api/workOrderStartRecord/save', {
												workOrderId: route.query.id,
												isFirst: false,
												firstWorkId: res.data[0].id
											})
											.then((resq) => {
												if (resq.code === 200) {
													ElMessage.success('开工成功');
													getList();

												} else {
													ElMessage.warning(res.message);
												}
											});
									});
							} else {
								axiosInstance
									.post('/api/workOrderStartRecord/save', {
										workOrderId: route.query.id,
										isFirst: true
									})
									.then((resq) => {
										if (resq.code === 200) {
											ElMessage.success('开工成功');
											getList();

										} else {
											ElMessage.warning(res.message);
										}
									});
							}
						}
					);

				}
			}
		)
	;

};

const handleResponse = (successMsg) => (res) => {
	if (res.code === 200) {
		ElMessage.success(successMsg);
		getList();
	} else {
		ElMessage.warning(res.message);
	}
};


const outInSum = async (formEl: FormInstance | undefined) => {
	await formEl.validate((valid, fields) => {
		if (valid) {
			const param = returnFeedingForm.value;
			param.workId = route.query.id;
			axiosInstance.post('/api/workOrder/returnMaterial', param)
				.then((res) => {
					if (res.code !== 200) {
						ElMessage.warning(res.message);
						return false;
					}
					returnFeedingShow.value = false;
					getList();
				});
		}
	});

};

const outFatherInfo = ref({});

const handleConfigDelete = (e) => {
	formData.value.details.splice(e, 1);
};


const storageOutList = ref([]);
const productBom = ref([]);

const getOption = () => {
	equipmentAll().then(res => {
		storageOutList.value = res.data;
	});

	axiosInstance.get('/api/throwMaterialRecord/queryMaterialList', { params: { workId: route.query.id } }).then(res => {
		if (res.code !== 200) {
			ElMessage.error(res.message);
			return false;
		}
		productBom.value = res.data;
	});

};

const reportList = ref([]);
const handleSelectionChange = (e) => {
	reportList.value = e;
};

const transferTypeFormatter = (row, column, cellValue) => {
	const typeOptions = {
		transfer: '调拔',
		instock: '入库',
		outstock: '出库'
	};
	return typeOptions[cellValue] || '';
};

const revokeJob = () => {
	ElMessageBox.confirm('是否确认撤销报工?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const param = reportList.value[0];
			axiosInstance.post('/api/workOrder/revocationWork',
				{ id: param.id }
			).then(res => {
				if (res.code !== 200) {
					ElMessage.error(res.message);
					return false;
				}
				ElMessage.success('操作成功');
				getList();
			});
		});
};

const getTypeName = (type: string) => {
	const name = typeList.value.find((item: any) => item.value === type);
	return name ? name.label : '';
};

const typeList = ref([
	{ label: '未完成', value: '0' },
	{ label: '已完成', value: '1' }
]);
//0123开机，调机，调模，换班


const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框

const returnFeedingShow = ref(false);

const returnFeedingForm = ref({
	count: null,
	materialId: null,
	batchNo: null
});
// 退料
const returnFeeding = () => {
	returnFeedingShow.value = true;
	returnFeedingForm.value = {};
};
const returnNoList = ref([]);
const returnMaterChange = (e) => {
	axiosInstance
		.post('/api/workOrder/batchNoByWorkIdMaterIa', {
			workId: route.query.id,
			materialId: e
		})
		.then((res) => {
			returnNoList.value = res.data;
		});
};

const bathNoChange = (e) => {
	returnNoList.value.forEach((item) => {
		if (item.batch == e) {
			returnFeedingForm.value.lockCount = item.count;
		}
	});
};

// 新建记录
const handleAdd = () => {
	// popType.value = 0;
	// isEdit.value = false;
	// formData.value = {
	// 	details: [{
	// 		materialId: null,
	// 		materialCount: null,
	// 		batchNo: null
	// 	}]
	// };
	showCrud.value = true;
};
// 判断质检类型
const getQualityTypeByValue = (e) => {
	let name = null;
	for (const item of qualityTypeList) {
		if (e == item.value) {
			name = item.label;
		}
	}
	return name;
};

// 质检类型
const qualityTypeList = reactive([
	{
		label: '首件检',
		value: '1',
		type: 'material'
	},
	{
		label: '末件检',
		value: '2',
		type: 'material'
	},
	{
		label: '生产',
		value: '3',
		type: 'material'
	},
	{
		label: '巡检',
		value: '4',
		type: 'material'
	},
	{
		label: '入库检',
		value: '5',
		type: 'procedure'
	},
	{
		label: '出库检',
		value: '6',
		type: 'procedure'
	},
	{
		label: '来料检',
		value: '7',
		type: 'procedure'
	}
	// 继续添加更多检查类型...
]);
const qualityReasonList = ref([
	{
		label: '开机',
		value: 0
	},
	{
		label: '调机',
		value: 1
	},
	{
		label: '调模',
		value: 2
	},
	{
		label: '换班',
		value: 3
	}
]);

const popType = ref(0);//0 编辑 1 只读
const schemeTaskList = ref([]);
const formatCompleteSetStatus = (e) => {
	const list = [{
		label: '不满足',
		value: '0'
	}, {
		label: '部分满足',
		value: '1'
	}, {
		label: '完全满足',
		value: '2'
	}];
	const type = list.find(type => type.value == e.completeSetStatus);
	return type ? type.label : '';
};
const statusType = (e) => {
	const list = [{
		label: '不合格',
		value: '0'
	}, {
		label: '合格',
		value: '1'
	}, {
		label: '报废',
		value: '2'
	}];
	const type = list.find(type => type.value == e.status);
	return type ? type.label : '';
};
const qualityTypeChange = (e) => {
	schemeTaskList.value = [];
	formData.value = {
		qualityType: e
	};
	const param = {
		qualityType: e,
		current: 1,
		pageSize: 99999
	};
	axiosInstance.post('/api/basedataQualityScheme/getPage', param)
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			schemeTaskList.value = res.data.records;
		});
};
// sourceNo: paginatedData.value.workNo


const doFinish = (row) => {
	ElMessageBox.confirm('是否确认完成?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			axiosInstance.post('/api/warehouseMaterialTransferOrder/finish', { id: row.id })
				.then(res => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('完结成功');
					getList();
				});
		})
		.catch(() => {
			// 处理取消的情况，如果需要的话
		});
};

const formatStatus = (row, column, cellValue) => {
	switch (cellValue) {
		case 1:
			return '待处理';
		case 2:
			return '进行中';
		case 3:
			return '完结';
	}
};


const qualityWayList = reactive([
	{
		label: '全检',
		value: '1'
	}, {
		label: '比例抽检',
		value: '2'
	}, {
		label: '固定抽检',
		value: '3'
	}, {
		label: '自定义抽检',
		value: '4'
	}
]);


const qualityPlanChange = (e) => {
	let param = {};
	for (const item of schemeTaskList.value) {
		if (item.id == e) {
			param = item;
		}
	}
	let json = JSON.parse(param.qualityJson);
	formData.value = { ...formData.value, ...json };
	formData.value.qualityJson = param.qualityJson;
	console.log(formData.value, 'param');
};


// 保存记录
const handleSave = async () => {
	const param = formData.value;
	param.qualityJson = JSON.stringify(param);
	console.log(param, 'param');
	if (!param.qualityPlan) {
		ElMessage.error('请选择质检方案');
		return false;
	}
	// if (!param.count || param.count == 0) {
	//     ElMessage.error('请输入数量');
	//     return false;
	// }
	param.id = null;
	param.status = false;
	param.sourceNo = paginatedData.value.workNo;
	let url = '/api/qualitySchemeTask/createMaterialTask';
	if (param.qualityType == 1 || param.qualityType == 2 || param.qualityType == 3 || param.qualityType == 4) {
		url = '/api/qualitySchemeTask/createWorkOrderTask';
	}
	axiosInstance.post(url, param)
		.then((res) => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			showCrud.value = false;
			getList();
		});
};


const rowChildren = (row: any) => {
	axiosInstance.post('/api/warehouseMaterialTransferOrder/getDetailById', { id: row.id }).then(res => {
		if (res.code !== 200) {
			ElMessage.warning(res.message);
			return false;
		}
		const listGroup = paginatedData.value.map((item) => {
			if (item.id === row.id) {
				return { ...item, children: res.data.children };
			}
			return item;
		});
		paginatedData.value = listGroup;
	});
	// axiosInstance.post('/api/basedataQualityScheme/getAll', {planId: row.id})
	//     .then(res => {
	//       if (res.code !== 200) {
	//         ElMessage.error(res.message);
	//         return false
	//       }
	//
	//       .value = res.data
	//     });

	// ProductionPlanDetailApi().then((res) => {
	//   if (res.code !== 200) {
	//     ElMessage.warning(res.message);
	//     return false;
	//   }
	//   const listGroup = paginatedData.value.map((item) => {
	//     if (item.id === row.id) {
	//       return {...item, children: res.data.records};
	//     }
	//     return item;
	//   });
	//   paginatedData.value = listGroup;
	// });
};

const tableData = ref([]);
const tableData1 = ref([]);
const tableData2 = ref([]);
const tableData3 = ref([]);
// 获取列表
const getList = async () => {
	axiosInstance.post('/api/workOrder/queryByWorkId', {
		id: route.query.id
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			paginatedData.value = res.data;
			// localStorage.setItem('workInfo', res.data)
			tableData.value = res.data.materStatusVOS;//齐套
			tableData1.value = res.data.throwMaterialRecordVOS;//投料记录
			tableData2.value = res.data.reportWorkRecords; //报工
			tableData3.value = res.data.qualitySchemeTaskList; //质量信息区
		});

	// 投料信息
	// axiosInstance.post('/api/throwMaterialRecord/getAll', {
	//   id: route.query.id
	// }).then(res => {
	//   if (res.code !== 200) {
	//     ElMessage.warning(res.message);
	//     return false
	//   }
	//   tableData1.value = res.data
	// }).catch(err => {
	//   ElMessage.warning('获取页面数据失败');
	// })
};

onMounted(() => {
	getList();
	getOption();
});
</script>
<style scoped lang="scss">
.info-body {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	flex-wrap: wrap;
}

.info-cil {
	width: 25%;
	height: 80px;
	border-radius: 10px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding-left: 20px;
}

.info-cil:hover {
	background: #f4f6f8;
}

.info-title {
	font-size: 16px;
}

.info-param {
	margin-top: 5px;
	color: #999;
}
</style>
